package com.dap.batch.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description: aop功能实现
 * 添加@Aspect注解
 * @Component注解 添加到spring容器中
 * @author: Fesine
 * @createTime:2017/9/26 20:07
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/9/26 20:07
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 拦截UserController所有方法所有参数
     */
    @Pointcut("execution(public * com.dap.batch.controller.*.*(..))")
    public void log() {

    }

    /**
     * 执行方法前处理
     */
    @Before("log()")
    public void doBefore(JoinPoint jp) throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}", request.getRequestURL());
        //请求method
        logger.info("method={}", request.getMethod());
        //ip
        logger.info("ip={}", request.getRemoteHost());
        /**
         * 类方法
         * jp.getSignature().getDeclaringTypeName()-->类
         * jp.getSignature().getName()-->方法名
         */
        logger.info("class_method={}", jp.getSignature().getDeclaringTypeName() + "." + jp
                .getSignature().getName());
        //参数
        logger.info("args={}", JSON.toJSONStringWithDateFormat(jp.getArgs(), "yyyy-MM-dd " +
                "HH:mm:ss"));
    }


    @AfterReturning(returning = "object", pointcut = "log()")
    public void afterReturning(Object object) {
        logger.info("object={}", JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss"));
    }
}
